/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.front.web.pay.ali;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.thinkgem.jeesite.common.utils.ali.config.AlipayConfig;
import com.thinkgem.jeesite.common.utils.ali.util.AlipaySubmit;
import com.thinkgem.jeesite.common.utils.ali.util.UtilDate;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.config.entity.ali.ConfigAlipay;
import com.thinkgem.jeesite.modules.config.service.ali.ConfigAlipayService;
import com.thinkgem.jeesite.modules.pay.entity.log.EcPayLog;
import com.thinkgem.jeesite.modules.pay.service.log.EcPayLogService;
import com.thinkgem.jeesite.modules.refund.entity.log.EcRefundLog;
import com.thinkgem.jeesite.modules.refund.service.log.EcRefundLogService;
import com.thinkgem.jeesite.modules.shop.constant.order.ShopOrderConstant;
import com.thinkgem.jeesite.modules.shop.entity.order.ShopOrder;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;

/**
 * 退款Controller（支付宝）
 * 
 * @author Egan
 * @version 2016-02-15
 */
@Controller
@RequestMapping(value = "${frontPath}/refund/ali")
public class ALIRefundController extends BaseController {
	private static Log log = LogFactory.getLog(ALIRefundController.class);
	
	@Autowired EcRefundLogService ecRefundLogService;
	
	@Autowired ShopOrderService shopOrderService;
	
	@Autowired EcPayLogService ecPayLogService;
	
	@Autowired ALIPayService aliPayService;
	
	@Autowired ConfigAlipayService configAlipayService;
	
	@RequestMapping(value = "forRefund")
	public String forRefund(ShopOrder shopOrder,HttpServletRequest req, HttpServletResponse resp,Model model) {
		try {
			
			ConfigAlipay configAlipay = configAlipayService.getConfigAlipay();
			shopOrder = shopOrderService.get(shopOrder);
			Map<String,String> resultMap = new HashMap<String, String>();
			Map<String,String> paramMap = new HashMap<String, String>();
			
			EcPayLog ecPayLog = new EcPayLog();
			ecPayLog.setCoNum(shopOrder.getCode());
			ecPayLog.setOrgCode(configAlipay.getSellerId());
			ecPayLog = ecPayLogService.getEcPayLogByCoNumOrgCode(ecPayLog);
			if ("1".equals(ecPayLog.getPayFlag())) {
				//2.查询该订单是否退过款
				EcRefundLog refundLog = new EcRefundLog();
				refundLog.setOutTradeNo(ecPayLog.getOrderNo());
				refundLog.setMchId(configAlipay.getSellerId());
				EcRefundLog refundLog2 = ecRefundLogService.getEcRefundLogByCoNumMchId(refundLog);
				if (refundLog2 == null) {
					//2.查询该订单是否退过款
					String txnAmt = String.valueOf(shopOrder.getTotalAmount());
			        int index = txnAmt.indexOf(".");
					if (index < 0) {
						txnAmt = txnAmt + ".00";
					} else if ((txnAmt.length() - index) < 3) {
						if ((txnAmt.length() - index) == 2) {
							txnAmt = txnAmt + "0";
						} else if ((txnAmt.length() - index) == 1) {
							txnAmt = txnAmt + "00";
						}
					} else if ((txnAmt.length() - index) > 3) {// 保留小数超过两位则去除多余的
						txnAmt = txnAmt.substring(0, index + 3);
					}
					paramMap.put("_input_charset", "utf-8");
					paramMap.put("batch_no", ecPayLog.getOrderNo());
					paramMap.put("batch_num", "1");
					paramMap.put("detail_data",ecPayLog.getOrderNo()+ "^" +txnAmt+"^协商退款");
					paramMap.put("notify_url", AlipayConfig.notify_url_refund);
					paramMap.put("partner", configAlipay.getPartner());
					paramMap.put("refund_date", UtilDate.getDateFormatter());
					paramMap.put("seller_email", configAlipay.getSellerEmail());
					paramMap.put("service", "refund_fastpay_by_platform_pwd");
					paramMap.put("sign_type", "MD5");
					String sHtmlText = AlipaySubmit.buildRequest(paramMap,"get","1",configAlipay );
					model.addAttribute("sHtmlText", sHtmlText);
				} else {
					resultMap.put("message", "该订单已退款！无法再次退款！");
				}
			} else if ("0".equals(ecPayLog.getPayFlag())) {
				resultMap.put("message", "该订单支付失败！无法退款！");
			} else {
				//TODO
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "modules/pay/ali/refund";
	}
	@RequestMapping(value = "forResult")
	public void forResult(HttpServletRequest request, HttpServletResponse resp, Model model) {
		try {
			if (log.isDebugEnabled()) {
				log.debug("Enter method forResult()..");
			}
			Map requestParams = request.getParameterMap();
			if (log.isDebugEnabled()) {
				log.debug("requestParams:" + requestParams.toString());
			}
			String result_details = new String(request.getParameter("result_details").getBytes("ISO-8859-1"),"UTF-8");
			String notify_time = new String(request.getParameter("notify_time").getBytes("ISO-8859-1"),"UTF-8");
			String notify_type = new String(request.getParameter("notify_type").getBytes("ISO-8859-1"),"UTF-8");
			String notify_id = new String(request.getParameter("notify_id").getBytes("ISO-8859-1"),"UTF-8");
			String batch_no = new String(request.getParameter("batch_no").getBytes("ISO-8859-1"),"UTF-8");
			String success_num = new String(request.getParameter("success_num").getBytes("ISO-8859-1"),"UTF-8");
			
			if (log.isDebugEnabled()) {
				log.debug("result_details:" + result_details);
				log.debug("notify_time:" + notify_time);
				log.debug("notify_type:" + notify_type);
				log.debug("notify_id:" + notify_id);
				log.debug("batch_no:" + batch_no);
				log.debug("success_num:" + success_num);
			}
			int index = result_details.indexOf("^");
			int index2 = result_details.lastIndexOf("^");
			if ("SUCCESS".equals(result_details.substring(index2 +1 ))){
				EcRefundLog refundLog = new EcRefundLog();
				refundLog.setCouponRefundCount(success_num);
				refundLog.setCouponRefundFee(result_details.substring(index +1 ,index2));
				refundLog.setOutRefundNo(batch_no);
				refundLog.setOutTradeNo(batch_no);
				refundLog.setRefundFee(result_details.substring(index +1 ,index2));
				refundLog.setRefundId(notify_id);
				ecRefundLogService.save(refundLog);
				EcPayLog paylog = ecPayLogService.getEcPayLogByOrderNo(batch_no);
				ShopOrder order = new ShopOrder();
	        	order.setCode(paylog.getCoNum());
	        	order.setStatus(ShopOrderConstant.ORDER_REFUND_SUCCESS);
	        	shopOrderService.updateOrderForPaySuccess(order);
			}
			
		} catch (Exception e){
			e.printStackTrace();
		}
	}
}